package network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import controller.GUIController;
import controller.TCPServerController;

public class TCPChatNIServer extends ChatNIServer {

	protected ServerSocket listeningSocket;
	protected int port;
	private boolean isrunning;
	
	private GUIController guicontroller;
	
	public TCPChatNIServer(int port) {
		super( TCPServerController.getInstance() );
		this.guicontroller = GUIController.getInstance();
		this.port = port;
	}

	@Override
	public void run() {
		isrunning = true;
		
		try
		{
			(new SecurityManager()).checkListen(port);
			listeningSocket = new ServerSocket(port);
			
			guicontroller.writeDebugScreen("TCPChatNIServer > Waiting for a new connection\n");
			
			do
			{			
				waitForClient();
				
			} while(isrunning);
		}
		catch(SecurityException securityException)
		{
			guicontroller.writeDebugScreen("TCPChatNIServer > the port " + port + " is already in use\n");
		}
		catch(IOException ioException)
		{
			ioException.printStackTrace();
		}
	}
	
	private void waitForClient()
	{
		try
		{
			Socket sockNewClient = listeningSocket.accept();
			
			((TCPServerController) this.controller).newClients.add( sockNewClient );
			
			guicontroller.writeDebugScreen("TCPChatNIServer > new connection from " + sockNewClient.getInetAddress().getHostAddress() + ":" + sockNewClient.getLocalPort() + "\n");
		}
		catch(SocketException e)
		{
			guicontroller.writeDebugScreen("TCPChatNIServer > shut down\n");
		}
		catch(IOException ioException)	
		{
			ioException.printStackTrace();
		}
	}
	
	public void kill()
	{
		try
		{
			isrunning = false;
			listeningSocket.close();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
}

